package com.xiaoxin.yixinai._frame.base;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.xiaoxin.yixinai._frame.utils.Config;
import com.xiaoxin.yixinai.userinfo.UserInfo;

public class BaseController {
	
	private static Logger log = LoggerFactory.getLogger(BaseController.class);
	
	private String AJAX_HEADER = "X-Requested-With";
	
	@Resource
	protected HttpServletRequest request;
	
	@Resource
	protected HttpServletResponse response;
	
	@Resource
	protected Config config;
	
	/**
	 * 获取当前登录人
	 * @return
	 */
	protected UserInfo getLoginUser() {
		UserInfo u = (UserInfo) request.getSession().getAttribute("loginUser");
		return u;
	}
	
	
	@ExceptionHandler(value = Exception.class)
	public String handleException(Exception e) throws ServletException, IOException{
		e.printStackTrace();
		log.error("error message =["+e.getMessage()+"]");
		String ajaxHeader = request.getHeader(AJAX_HEADER);
		// 如果拦截到没有权限的请求时，是没有赋ctx的。 这时候进入error页面时会显示错误。
		request.setAttribute("ctx", request.getContextPath());
		String errorMsg = e.getMessage() == null ? "服务异常" : e.getMessage();
		
		if (StringUtils.isEmpty(ajaxHeader)) {
			request.setAttribute("errorMsg", errorMsg);
			return "/error";
		}else{
			response.getWriter().write(new Gson().toJson(ERROR(errorMsg)));
			response.getWriter().flush();
		}
		return null;
	}
	
	public Object SUCCESS(Object data){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("result", "success");
		result.put("data", data);
		return result;
	}
	
	public Object SUCCESS(){
		return SUCCESS(null);
	}
	
	public Object ERROR(String desc){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("result", "fail");
		result.put("data", desc);
		return result;
	}
	
	protected String persistFile(MultipartFile[] files) throws IOException {
		if(files!=null && files.length>0) {
			JsonArray array = new JsonArray();
			for (int i = 0; i<files.length; i++) { 
				MultipartFile file = files[i];
				if(file != null && file.getSize() > 0) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
					String fileName = file.getOriginalFilename();
					File dir = new File(config.getUploadFilePath());
					dir.mkdirs();
					Date now = new Date();
					File f = new File(config.getUploadFilePath(), sdf.format(now)+fileName);
					f.createNewFile();
					file.transferTo(f);
					JsonObject object = new JsonObject();
					String path="/workform/file/" + sdf.format(now)+fileName;
					object.addProperty("fileName", fileName);
					object.addProperty("fileUrl", path);
					array.add(object);
				}
			}
			return array.toString();
		}
		return null;
	}
	
}
